package com.liferay.portal.model;

import java.util.Date;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.ModelListenerException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portlet.shopping.model.ShoppingCategory;
import com.liferay.portlet.shopping.model.ShoppingItem;
import com.liferay.portlet.shopping.service.ShoppingItemLocalServiceUtil;
import com.liferay.util.portlet.PortletProps;

public class ShoppingCategoryListener extends BaseModelListener<ShoppingCategory> {
	@Override
	public void onAfterCreate(ShoppingCategory model)
			throws ModelListenerException {
		// TODO Auto-generated method stub
		
		try {
			insertDefaultItem(model);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onAfterCreate(model);
	}

	private void insertDefaultItem(ShoppingCategory model) throws SystemException {
		// TODO Auto-generated method stub
		
		long itemId = 0l;
		try {
			itemId = CounterLocalServiceUtil.increment();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ShoppingItem shoppingItem = ShoppingItemLocalServiceUtil.createShoppingItem(itemId);
		
		shoppingItem.setName(PortletProps.get("where.most.needed.name"));
		shoppingItem.setDescription(PortletProps.get("where.most.needed.desc"));
		shoppingItem.setSmallImageURL(PortletProps.get("default.category.image.url"));
		
		shoppingItem.setCompanyId(model.getCompanyId());
		shoppingItem.setCategoryId(model.getCategoryId());
		shoppingItem.setUserId(model.getUserId());
		shoppingItem.setUserName(model.getUserName());
		shoppingItem.setUserUuid(model.getUserUuid());
		
		shoppingItem.setPrice(0.0);
		shoppingItem.setStockQuantity(2147483647);
		shoppingItem.setSku(getSKU());
		shoppingItem.setCreateDate(new Date());
		
		ShoppingItemLocalServiceUtil.addShoppingItem(shoppingItem);
	}

	private String getSKU() {
		StringBuilder sb = new StringBuilder("HR");	
		
		long index = 0l;
		try {
			index = CounterLocalServiceUtil.increment("com.hoperay.shopping.sku");
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String width = "5";
		
		sb.append(String.format("%0" + width + "d", index));
	
		return sb.toString();
	}
}